module ahb_mem (
           clk,
           reset_n,
           sHADDR,
           sHWDATA,
           sHWRITE,
           sHREADYOUT,
           sHSIZE,
           sHBURST,
           sHSEL,
           sHTRANS,
           sHRDATA,
           sHRESP,
           sHREADY,

           print
       );

parameter MEMSIZE = 256;
reg [31:0] mem[MEMSIZE-1:0];

input clk;
input reset_n;

input [31:0]    sHADDR;
input [31:0]    sHWDATA;
input           sHWRITE;
input [2:0]     sHSIZE;
input [2:0]     sHBURST;
input           sHSEL;
input [1:0]     sHTRANS;
input           sHREADY;

input           print;

reg [1:0]   next_HTRANS;
reg [31:0]  next_HADDR;
reg         next_HWRITE;

reg         out_HRESP;

output          sHREADYOUT;
output [31:0]   sHRDATA;
output [1:0]    sHRESP;


assign sHRESP = {1'b0, out_HRESP};
assign sHRDATA = mem[next_HADDR / 4];
assign sHREADYOUT = 1;


integer i;

initial begin
    for(i = 0; i < MEMSIZE; i = i + 1) begin
        mem[i] = i * 4;
    end
    $readmemb("./sha256_k.mif", mem, 0, 64);
end


always @(posedge clk or negedge reset_n) begin
    if(!reset_n) begin
        out_HRESP <= 1'b0;
        next_HWRITE <= 1'b0;
        next_HTRANS <= 2'b0;
        next_HADDR <= 32'h0;
    end else begin
        if(sHSEL & sHREADY) begin
            next_HADDR <= sHADDR;
            next_HTRANS <= sHTRANS;
            next_HWRITE <= sHWRITE;
            if(sHSIZE != 3'b010 & sHTRANS != 2'b0) begin
                out_HRESP <= 1'b1;
            end else begin
                out_HRESP <= 1'b0;
            end
        end
    end
end

always @(posedge clk or negedge reset_n) begin
    if(!reset_n) begin
    end else begin
        if(next_HTRANS == 2'b10) begin
            if(next_HWRITE) begin
                mem[next_HADDR / 4] <= sHWDATA;
                $display("Write %x @ %x", sHWDATA, next_HADDR);
            end else begin
                $display("Read %x @ %x", sHRDATA, next_HADDR);
            end
        end
    end
end

always @(posedge clk) begin
    if(print) begin
        for(i = 0; i < MEMSIZE; i=i+1) begin
            if(i % 4 == 0) begin
                $write("|0x%08x|", i * 4);
            end

            $write(" %08x", mem[i]);

            if(i % 4 == 3) begin
                $write("\n");
            end
        end
    end
end

endmodule
